package com.atguigu.domain.strategy.service.armory;

import com.atguigu.domain.strategy.model.entity.StrategyAwardEntity;
import com.atguigu.domain.strategy.model.entity.StrategyEntity;
import com.atguigu.domain.strategy.model.entity.StrategyRuleEntity;
import com.atguigu.domain.strategy.respository.IStrategyRepository;
import com.atguigu.types.common.Constants;
import com.atguigu.types.enums.ResponseCode;
import com.atguigu.types.exception.AppException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.security.SecureRandom;
import java.util.*;

//初始化策略装配
@Service
@Slf4j
public class StrategyArmory implements IStrategyArmory, IStrategyDispatch{

    @Resource
    private IStrategyRepository repository;

    @Override
    public boolean assembleStrategy(long strategyId) {
        //查询策略配置
        List<StrategyAwardEntity> strategyAwardEntityList= repository.queryStrategyAwardList(strategyId);

        //缓存奖品库存
        for(StrategyAwardEntity strategyAwardEntity:strategyAwardEntityList){
            Integer awardId = strategyAwardEntity.getAwardId();
            Integer awardCount = strategyAwardEntity.getAwardCount();
            cacheStrategyAwardCount(strategyId,awardId,awardCount);
        }

        //默认装配配置
        assembleStrategy(String.valueOf(strategyId),strategyAwardEntityList);

        //权重策略配置，全部抽奖概率
        StrategyEntity strategyEntity = repository.queryStrategyEntityById(strategyId);
        String ruleWeight = strategyEntity.getRuleWeight();
        if(ruleWeight==null) return true;

        StrategyRuleEntity strategyRuleEntity = repository.queryStrategyRule(strategyId, ruleWeight);
        if (strategyRuleEntity==null){
            throw new AppException(ResponseCode.STRATEGY_RULE_WEIGHT_IS_NULL.getCode(), ResponseCode.STRATEGY_RULE_WEIGHT_IS_NULL.getInfo());
        }
        Map<String, List<Integer>> ruleWeightValueMap = strategyRuleEntity.getRuleWeightValues();
        Set<String> keys = ruleWeightValueMap.keySet();
        for(String key:keys){
            List<Integer> values = ruleWeightValueMap.get(key);
            ArrayList<StrategyAwardEntity> strategyAwardEntityListClone = new ArrayList<>(strategyAwardEntityList);
            strategyAwardEntityListClone.removeIf(entity -> !values.contains(entity.getAwardId()));
            assembleStrategy(String.valueOf(strategyId).concat("_").concat(key),strategyAwardEntityListClone);
        }
        return true;
    }

    @Override
    public boolean assembleLotteryStrategyByActivityId(Long activityId) {
        Long strategyId = repository.queryStrategyIdByActivityId(activityId);
        return assembleStrategy(strategyId);
    }

    private void cacheStrategyAwardCount(Long strategyId,Integer awardId, Integer awardCount) {
        String cacheKey = Constants.RedisKey.STRATEGY_AWARD_COUNT_KEY + strategyId + Constants.UNDERLINE+awardId;
        repository.storeStrategyAwardCount(cacheKey, awardCount);
    }

    private void assembleStrategy(String strategyId, List<StrategyAwardEntity> strategyAwardEntityList) {
        //获取最小概率值
        BigDecimal minRate = strategyAwardEntityList.stream().map(StrategyAwardEntity::getAwardRate).min(BigDecimal::compareTo).orElse(BigDecimal.ZERO);

        //获取概率总和
        BigDecimal totalRate =strategyAwardEntityList.stream().map(StrategyAwardEntity::getAwardRate).reduce(BigDecimal.ZERO, BigDecimal::add);
        // 4. 用 1 % 0.0001 获得概率范围，百分位、千分位、万分位
        BigDecimal rateRange = totalRate.divide(minRate, 0, RoundingMode.CEILING);
        // 5. 生成策略奖品概率查找表「这里指需要在list集合中，存放上对应的奖品占位即可，占位越多等于概率越高」
        ArrayList<Integer> strategyAwardSearchRateTables = new ArrayList<>(rateRange.intValue());
        for(StrategyAwardEntity strategyAwardEntity:strategyAwardEntityList){
            Integer awardId = strategyAwardEntity.getAwardId();
            BigDecimal awardRate = strategyAwardEntity.getAwardRate();
            // 计算出每个概率值需要存放到查找表的数量，循环填充
            for (int i = 0; i < awardRate.multiply(rateRange).setScale(0, RoundingMode.CEILING).intValue(); i++) {
                strategyAwardSearchRateTables.add(awardId);
            }
        }
        //打乱处理
        Collections.shuffle(strategyAwardSearchRateTables);
        // 7. 生成出Map集合，key值，对应的就是后续的概率值。通过概率来获得对应的奖品ID
        Map<Integer, Integer> shuffleStrategyAwardSearchRateTable = new LinkedHashMap<>();
        for (int i = 0; i < strategyAwardSearchRateTables.size(); i++) {
            shuffleStrategyAwardSearchRateTable.put(i, strategyAwardSearchRateTables.get(i));
        }
        //存放入redis
        repository.storeStrategyAwardSearchRateTable(strategyId, shuffleStrategyAwardSearchRateTable.size(),shuffleStrategyAwardSearchRateTable);

    }

    @Override
    public Integer getRandomAwardId(long strategyId) {
        int range = repository.getRateRange(strategyId);
        return repository.getStrategyAwardAssemble(String.valueOf(strategyId), new SecureRandom().nextInt(range));
    }

    @Override
    public Integer getRandomAwardId(long strategyId, String ruleWeightValue) {
        String key = String.valueOf(strategyId).concat("_").concat(ruleWeightValue);
        int range = repository.getRateRange(key);
        return repository.getStrategyAwardAssemble(key, new SecureRandom().nextInt(range));
    }

    @Override
    public Boolean subtractAwardStock(long strategyId, Integer awardId, Date endDateTime) {
        String cacheKey = Constants.RedisKey.STRATEGY_AWARD_COUNT_KEY + strategyId + Constants.UNDERLINE+awardId;
        return repository.subtractionAwardStock(cacheKey,endDateTime);
    }
}
